local mysql = require "resty.mysql"
local cjson = require "cjson"

local db_pool = ngx.shared.mysql_pool

--[[
    db_pool: 
        [
            init boolean, 
            size integer, 
            max_size integer, 
            idle {}, 
            busy {}, 
        ]
]]

-- 初始化连接池
local function init_mysql_db()
    local mysql_conf = {
        host = "127.0.0.1",
        port = 3306,
        database = "chat",
        user = "cauchy",
        password = "root",
        max_idle_timeout = 10000, -- 最大空闲时间
        pool_size = 100 -- 连接池大小
    }

    local db, err = mysql:new()
    if not db then
        ngx.log(ngx.ERR, "Failed to create mysql instance: ", err)
        return nil
    end

    db:set_timeout(1000)

    local ok, err, errno, sqlstate = db:connect(mysql_conf)
    if not ok then
        ngx.log(ngx.ERR, "Failed to connect to database: ", err)
        return nil
    end

    return db 
end

local function create_pool()
    db_pool = {}
    db_pool.idle = {}
    db_pool.busy = {}
    db_pool.size = 0
    db_pool.init = true 
    db_pool.max_size = 100
    return true 
end 

-- 获取数据库连接
local function get_mysql_db() 
    if not db_pool or not db_pool.init then 
        create_pool()
    end 
    local db 
    if #db_pool.idle > 0 then 
        db = table.remove(db_pool.idle)
    elseif db_pool.size < db_pool.max_size then 
        db = init_mysql_db()
        if db then 
            db_pool.size = db_pool.size + 1
        end 
    end
    if db then 
        table.insert(db_pool.busy, db)
    end 
    return db
end 

local function release_mysql_db(db)
    for i, v in ipairs(db_pool.busy) do 
        if v == db then 
            table.remove(db_pool.busy, i)
            table.insert(db_pool.idle, db)
            break 
        end 
    end 
end 

local function mysql_query(db, sql)
    local res, err = db:query(sql)
    if not res then
        ngx.log(ngx.ERR, "Failed to query mysql instance: ", err)
        return nil
    end
    return res
end

local _M = {}

-- 在处理请求之前获取数据库连接
function _M.process_mysql_query(sql)
    local db = get_mysql_db()

    local res = false 
    res = mysql_query(db, sql)
    release_mysql_db(db)
    return res 
end

return _M